package stz.flash.main;

import stz.flash.main.flashlight.model.Flashlight;
import stz.flash.main.strobe.model.VRController;
import stz.flash.option.Option;
import stz.flash.option.PersistentData;


public class CloseHandle {
	
	public static void close(){
		stopTimer();
		afterJoin();
	}

	private static void stopTimer(){
		FlashTimer.getIns().stop(FlashTimer.STOP, null);
	}
	
	// Led등등이 꺼질수 있도록 join으로 기다림 
	private static void afterJoin() {
		new Thread(){  
			public void run() {
				try {
					joinThreads();
					
					PersistentData.commit();
					
					popScreen();
					
					if (VRController.isVRForeground())
						FlashKeyEvent.postEscKey();

					if (Option.getIns().isBackgroundExecute() == false)
						System.exit(0);
				} catch (InterruptedException e) {
				}
			};
		}.start();
	}
	
	
	private static void popScreen(){
		ScreenHandle.getIns().popScreen();
	}
	
	private static void joinThreads() throws InterruptedException{
		if (getTimerThread() != null)
			getTimerThread().join();
		if (getFlashlightThread() != null)
			getFlashlightThread().join();
	}
	
	private static Thread getTimerThread(){
		return FlashTimer.getThread();
	}
	
	private static Thread getFlashlightThread(){
		return Flashlight.getThread();
	}
}